package com.twu.biblioteca;

import com.twu.biblioteca.content.BookContent;
import com.twu.biblioteca.content.MovieContent;
import com.twu.biblioteca.menuoption.*;
import com.twu.biblioteca.menuoption.books.CheckoutBook;
import com.twu.biblioteca.menuoption.books.ListBooks;
import com.twu.biblioteca.menuoption.books.ReturnBook;
import com.twu.biblioteca.menuoption.movies.CheckoutMovie;
import com.twu.biblioteca.menuoption.movies.ListMovies;
import com.twu.biblioteca.menuoption.users.ShowUserInformation;
import com.twu.biblioteca.users.BibliotecaUsers;

import java.io.*;
import java.util.List;
import java.util.LinkedList;
import java.io.BufferedReader;

/**
 * Created by mduemcke on 9/23/14.
 */
public class BibliotecaMenu {

    private List<MenuOptionAbstract> options;
    private BufferedReader reader;
    private BookContent bookContent;
    private MovieContent movieContent;
    private BibliotecaUsers bibliotecaUsers;
    private boolean quit;

    public BibliotecaMenu(BookContent bookContent, MovieContent movieContent, Reader reader) {
        options = new LinkedList<MenuOptionAbstract>();
        this.reader = new BufferedReader(reader);
        this.bibliotecaUsers = new BibliotecaUsers(this.reader);
        this.bookContent = bookContent;
        this.movieContent = movieContent;
        quit = false;
        addOptionsToMenu();
    }

    public void quitAtNextPossibility() {
        quit = true;
    }

    protected void displayMenu() {
        boolean userAuthenticated = bibliotecaUsers.authenticateUser();
        if(!userAuthenticated) {
            quit = true;
        }
        while(!quit) {
            System.out.println("\nPlease choose one of the options:");
            for (MenuOptionAbstract o : options) {
                o.printOption();
            }

            try {
                System.out.println("Type in your choice below:");
                String selectedOption = reader.readLine();
                parseOption(selectedOption.charAt(0));
            } catch (IOException ioe) {
                System.err.print(ioe.getStackTrace());
            }
        }
    }

    private void addOptionsToMenu() {
        options.add(new ListBooks(bookContent));
        options.add(new CheckoutBook(bookContent, reader));
        options.add(new ReturnBook(bookContent, reader));
        options.add(new ListMovies(movieContent));
        options.add(new CheckoutMovie(movieContent, reader));
        options.add(new ShowUserInformation(bibliotecaUsers));
        options.add(new Quit(this));
    }

    private void parseOption(char o) {
        for(MenuOptionAbstract m : options) {
            if(m.isSelectedOption(o)) {
                m.processOption();
                return;
            }
        }
        System.out.print("Select a valid option!\n");
    }
}
